from observable import Observable
from threading import Timer

class MockModel(object):
   def __init__(self):
      self.beat = Observable(0)
      self.bpm = self.beat
   def start(self):
      self.beat.value = self.beat.value
   def stop(self):
      self.beat.value = self.beat.value
   def set_bpm(self, bpm):
      self.bpm.value = bpm
   def get_bpm(self):
      return self.bpm.value

class Model(object):
    
   def __init__(self):
      self.beat = Observable(0)
      self.bpm = Observable()
      self._stop = True
      self.set_bpm(90)

   def _beat(self, bpm):
      if self._bpm != bpm:
         return
      self.beat.value = 1
      self._delay()

   def _delay(self):
      if not self._stop and self._bpm:
         t = Timer(60./self._bpm, self._beat, (self._bpm,))
         t.start()

   def start(self):
      self._stop = False
      self.set_bpm(self._bpm)

   def stop(self):
      self._stop = True
      self.set_bpm(0)

   def set_bpm(self, bpm):
      if bpm:
         self._bpm = bpm
      if not self._stop or bpm==0:
         self.bpm.value = bpm
      self._delay()

   def get_bpm(self):
      return self._bpm
